<?php

class Home extends M_Controller
{

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 首页
     */
    public function index()
    {
        parent::_index();
    }

    /**
     * 藏品列表
     */
    public function favoriteList()
    {
        $page = max($_GET['page'], 1);
        $pageSize = $_GET['pageSize'] ?? 10;
        $param = $this->input->get();
        $result = $this->models('favorite')->favoriteList(
            'id,catid,title,thumb,start_time,price,creator,nums,buy_nums',
            $page,
            $pageSize,
            array_filter($param),
        );
        apiSuccess(1, 'success', [
            'list' => array_map(function (&$item) {
                return $this->models('favorite')->favoriteTransfer($item);
            }, $result),
            'end' => count($result) < $pageSize
        ]);
    }

    // 藏品详情
    public function favoriteInfo()
    {
        try {
            $id = $this->input->get('id');
            if ((int)$id < 1) {
                throw new Exception('参数内容错误');
            }
            $info = $this->models('favorite')->favoriteInfo($id,
                'id,catid,title,thumb,price,nums,buy_nums,start_time,lock,creator');
            if (empty($info)) {
                throw new Exception('内容不存在');
            }
            $this->models('module')->addHits($info['id'], 'favorite');
            $info['buy_nums'] = $this->getNums($info);
            $info['lock'] = $this->models('favorite')->snLockStatus($info['id'], $info['buy_nums']) ? 1 : 0;
            $status = $this->models('favorite')->collectionStatus($info['id'], $this->uid)['status'];
            $data = $this->models('favorite')->getContent($info['id']);
            apiSuccess(1, 'success', [
                'info' => $this->models('favorite')->favoriteTransfer($info),
                'status' => $status == 1,
                'code' => $this->member['randcode'],
                'data' => $data
            ]);
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }
    }

    // 收藏内容
    public function favoriteCollection()
    {
        if ((int)$this->uid < 1) {
            apiSuccess(-4001, '请登录');
        }
        $id = $this->input->get('id');
        $info = $this->models('favorite')->favoriteInfo((int)$id, 'id,title');
        if (empty($info)) {
            apiSuccess(0, '内容不存在');
        }
        $collection = $this->models('favorite')->collectionStatus($info['id'], $this->uid);
        switch ($collection['status']) {
            case 1:
                $this->models('favorite')->upCollection($collection['id'], ['status' => 2]);
                $msg = '取消成功';
                break;
            case 2:
                $this->models('favorite')->upCollection($collection['id'], ['status' => 1]);
                $msg = '重新收藏';
                break;
            default:
                $this->models('favorite')->addCollection([
                    'cid' => $info['id'],
                    'uid' => $this->uid,
                    'title' => $info['title'],
                    'status' => 1
                ]);
                $msg = '收藏成功';
                break;
        }
        apiSuccess(1, $msg);
    }

    // 预购买藏品
    public function prepare()
    {
        try {
            /**
             * @var $info
             * @var $nums
             * @var $member
             */
            $result = $this->favorite();
            extract($result);
            $openID = $this->models('member')->wxInfo($this->uid, 'openid');
            if (empty($openID)) {
                apiSuccess(40003, '无法获取openid');
            }
            apiSuccess(1, 'success', ['info' => $info, 'number' => $nums]);
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }
    }

    // 确定购买
    public function buyFavorite()
    {
        try {
            $this->db->trans_begin();
            $result = $this->favorite();
            $oid = $this->models('favorite')->addOrder($result, 'favorite');
            if ((int)$oid < 1) {
                throw new Exception('入库失败,请稍后重试');
            }
            if (empty($this->models('favorite')->addOrderGood($oid, $result))) {
                throw new Exception('订单商品添加失败', 1);
            }
            $payID = $this->models('system/pay')->create(
                $this->uid,
                $result['info']['price'],
                'favorite',
                $oid,
                '购买' . $result['info']['title']
            );
            // 将支付id 更新到订单
            $this->models('favorite')->operateOrder($oid, ['pay_id' => $payID]);
            // 确定购买之后将此物锁住, 支付完成后解锁 / 或取消支付 / 或订单超时解锁
            $this->models('favorite')->operateLock($result['info']['id'], 1);
            $this->models('favorite')->addQueue($this->uid, $oid, 'favorite', $result['info']['id'], $result['nums']);
            $this->db->trans_commit();
            apiSuccess(1, 'success', ['oid' => $oid, 'payId' => encrypt($payID, 'mutaoinc')]);
        } catch (Exception $e) {
            if ($e->getCode() == 1) {
                $this->db->trans_rollback();
            }
            apiSuccess(0, $e->getMessage());
        }
    }

    /**
     * 购买藏品所需
     * @throws Exception
     */
    private function favorite(): array
    {
        if ((int)$this->uid < 1) {
            apiSuccess(-4001, '请登录');
        }
        ## 查看用户是否是被锁定购买
        $lockStatus = $this->models('favorite')->maxTimeAndNum($this->uid, strtotime("-1 hours"));
        if ($lockStatus['total'] >= 3 && time() - $lockStatus['end'] < 7200) {
            throw new Exception('您在1小时内同一账户产生' . $lockStatus['total'] . '个失效订单,锁定两小时');
        }
        $field = $this->input->post();
        if ((int)$field['id'] < 1) {
            throw new Exception('参数内容错误', 0);
        }
        $info = $this->models('favorite')->favoriteInfo(
            $field['id'],
            'id,catid,title,creator,title,thumb,price,nums,buy_nums,start_time,uid,author,lock'
        );
        if ($info['start_time'] > time()) {
            throw new Exception('尚未到达开启购买时间', 0);
        }
        if ($info['price'] < 0.01) {
            throw new Exception('价额设置错误,无法购买');
        }
        $nowNums = (int)$field['nums'];
        if ($nowNums < 1) {
            throw new Exception('商品编号错误');
        }
        if ($nowNums >= $info['nums']) {
            throw new Exception('已达购买最大限量', 0);
        }
        $lockStatus = $this->models('favorite')->snLockStatus($info['id'], $nowNums);
        if ($lockStatus) {
            throw new Exception('请稍等, 此编号正在购买');
        }
        if ($sn = $this->models('favorite')->getSn($info['id'])) {
            $sn = explode(',', $sn);
            if (in_array($nowNums, $sn)) {
                throw new Exception('此藏品已售出,请勿购买');
            }
        }
        $member = $this->models('member')->uidInfo(['uid' => $this->uid], 'uid,name,username,team_code');
        return ['info' => $info, 'nums' => $nowNums, 'member' => $member];
    }

    // 取出可用的编号
    protected function getNums($info)
    {
        if (empty($info)) {
            return 0;
        }
        ### 此藏品对应视图中的内容
        $sn = $this->models('favorite')->getSn($info['id']);
        ###  此商品中含有锁的藏品编号
        $lockSn = $this->models('favorite')->getLockSn($info['id']);
        if ($lockSn) {
            $lockSn = array_column($lockSn, 'sn');
        }
        require_once WEBPATH . 'web/libraries/CreateSn.php';
        return (new CreateSn([
            'sn' => $sn,
            'buy_nums' => $info['buy_nums'],
            'max' => $info['nums'],
            'lock' => $lockSn ?: []
        ]))->getResult();
    }

    //  我的待支付的藏品订单列表
    public function favoriteNoPay()
    {
        if ((int)$this->uid < 1) {
            apiSuccess(-4001, '请登录');
        }
        $page = max($_GET['page'], 1);
        $pageSize = (int)$_GET['pageSize'] ?: 10;
        $result = $this->models('favorite')->boxOrderList(
            ['buy_uid' => $this->uid, 'mid' => 'favorite', 'order_status' => 1, 'pay_status' => 0],
            $page,
            $pageSize
        );
        if (empty($result)) {
            apiSuccess(0, '暂无订单内容');
        }
        $oidArr = array_column($result, 'id');
        $goodList = $this->models('favorite')->goodsList($oidArr);
        foreach ($result as &$item) {
            foreach ($goodList as &$good) {
                $good['thumb'] = dr_thumb($good['thumb'], 500, 500);
                if ($good['oid'] == $item['id']) {
                    $item['goods'] = $good;
                }
            }
        }
        apiSuccess(1, 'success', [
            'list' => array_map(function (&$item) {
                return $this->models('favorite')->orderTransfer($item);
            }, $result),
            'end' => $pageSize > count($result)
        ]);
    }


}